import website from '@/config/website'
import useRouterStore from "@/stores/useRouterStore";
import useCommonStore from "@/stores/useCommonStore";
import {deepClone} from "utils/util";

const iframeComponent = 'components/iframe/main';


const modules = import.meta.glob(['../views/**/**/*.vue', "../page/**/**/*.vue", "../components/iframe/main.vue"])


function isURL(s) {
    return /^http[s]?:\/\/.*/.test(s)
}

let RouterPlugin = function () {
    this.$router = null;
    this.$pinia = null;
}

RouterPlugin.install = function (option = {}) {
    this.$router = option.router;

    const commonStore = useCommonStore();
    const routerStore = useRouterStore();

    let i18n = option.i18n.global
    this.$router.$avueRouter = {
        safe: this,
        // 设置标题
        setTitle: (title) => {
            const defaultTitle = i18n.t('title');
            title = title ? `${title} | ${defaultTitle}` : defaultTitle;
            document.title = title;
        },
        closeTag: (value) => {
            let tag = value || routerStore.tag;
            if (typeof value === 'string') {
                tag = routerStore.tagList.find(ele => ele.fullPath === value)
            }
            routerStore.delTag(tag);

        },
        generateTitle: (item, props = {}) => {
            let meta = item[props.meta || 'meta'] || {}
            let query = item[props.query || 'query'] || {}
            let params = item["params"] || {}
            query = Object.assign({}, query, params)

            let labelKey = props.labelKey || props.label || 'label'
            let title = item[labelKey] || query[labelKey] || query.name
            title = title || meta[labelKey] || query.name
            let key = meta.i18n
            if (key) {
                const hasKey = i18n.te('route.' + key)
                if (hasKey) return i18n.t('route.' + key)
            }
            return title
        },
        //动态路由
        formatRoutes: function (menus = [], first) {

            const aRouter = []
            const propsDefault = website.menuConfig
            if (menus && menus.length === 0) {
                return;
            }
            for (let i = 0; i < menus.length; i++) {
                const oMenu = menus[i];
                const routerItem = {}

                let path = oMenu[propsDefault.path];
                let component = oMenu[propsDefault.component] || oMenu.component;
                routerItem.path = path;

                routerItem.icon = oMenu[propsDefault.icon];
                routerItem.query = oMenu[propsDefault.query];
                routerItem.meta = oMenu[propsDefault.meta] || {};

                routerItem.meta[propsDefault.label] = routerItem.meta[propsDefault.label] || oMenu[propsDefault.label];

                if (website.routerOption.keepAlive) {
                    routerItem.meta.keepAlive = option.keepAlive
                }
                if (oMenu.menuKeepAlive === 1) {
                    routerItem.meta.keepAlive = oMenu.menuKeepAlive === 1
                }

                let children = oMenu[propsDefault.children];
                const isChild = !!(children && children.length > 0);
                routerItem.redirect = !isChild && first ? `${path}` : '';

                routerItem.component = (() => {
                    // 判断是否为首路由
                    if (first) {
                        return modules[commonStore.isMacOs ? '../page/index/layout.vue' : '../page/index/index.vue']
                    }
                    // 判断是否为多层路由
                    if (isChild && !first) {
                        return modules['../page/index/layout.vue']
                    }
                    //  最终的页面视图
                    let result = modules[`../${component}.vue`]

                    if (!result) {
                        return null;
                    }
                    result().then(mod => {
                        mod.default.name = path
                    }).catch(err => {
                        console.error("路由加载错误", component, routerItem)
                    })
                    return result
                })();


                // 处理是否为一级路由
                routerItem.children = !isChild ? (() => {

                    if (first) {
                        oMenu[propsDefault.path] = `${path}`;
                        let result = modules[`../${component}.vue`]
                        if (result == null) {
                            console.error("未能加载组件：", oMenu[propsDefault.path] , oMenu)
                            return []
                        }
                        result().then(mod => {
                            mod.default.name = path
                        })
                        return [{
                            component: result,
                            icon: routerItem.icon,
                            name: routerItem.name,
                            meta: routerItem.meta,
                            query: routerItem.query,
                            path: ''
                        }]
                    }
                    return [];
                })() : (() => {
                    return this.formatRoutes(children, false)
                })()

                if (!isURL(path)) {
                    aRouter.push(routerItem)
                }
            }

            if (!first) {
                return aRouter
            }
            aRouter.forEach((routeConfig) => {
                try {
                    // console.log(" this.$router", option.router)
                    // 使用addRoute方法添加路由，确保每个routeConfig都有必要属性如path和component
                    option.router.addRoute(routeConfig);
                } catch (error) {
                    console.error('Failed to add route:', routeConfig, 'Error:', error);
                }
            });

        }
    }
}


const iframeSrc = (href) => {
    return href.replace(/&/g, "#")
}
export const formatPath = (menu, first) => {

    const propsDefault = website.menuConfig;
    const iconKey = propsDefault.icon;
    menu[iconKey] = menu[iconKey] || propsDefault.iconDefault;
    menu[propsDefault.meta] = menu[propsDefault.meta] || {}


    const isChild = !!(menu[propsDefault.children] && menu[propsDefault.children].length !== 0);
    if (!isChild && first) {
        if (isURL(menu[propsDefault.path])) {
            let href = menu[propsDefault.path]
            menu[propsDefault.path] = createUrlRoutePath(menu[propsDefault.path])
            menu[propsDefault.component] = iframeComponent
            menu[propsDefault.query] = {url: iframeSrc(href)}
            menu[propsDefault.meta] = menu[propsDefault.meta] || {}
            if (menu[propsDefault.openType] === 1) {
                menu[propsDefault.meta].target = "_blank"

            }
        }
        return
    }
    const subMenus = menu[propsDefault.children];
    if (!subMenus) {
        return;
    }
    for (const subMenu of subMenus) {
        subMenu[propsDefault.meta] = subMenu[propsDefault.meta] || {}
        // console.log("subMenu",subMenu)
        if (isURL(subMenu[propsDefault.path])) {
            let href = subMenu[propsDefault.path]
            subMenu[propsDefault.path] = createUrlRoutePath(subMenu[propsDefault.path])
            subMenu[propsDefault.component] = iframeComponent
            subMenu[propsDefault.query] = {url: iframeSrc(href)}
            if (subMenu[propsDefault.openType] === 1) {
                subMenu[propsDefault.meta].target = "_blank"
            }
        }
        let path = `${menu[propsDefault.path]}/${subMenu[propsDefault.path]}`
        if (/\/\/+/.test(path)) {
            path = path.replaceAll(/\/\/+/g, "/")
        }
        subMenu[propsDefault.path] = path
        formatPath(subMenu);
    }


}

function createUrlRoutePath(urlPath) {
    let str = btoa(urlPath)
    let hex = '/url_';
    for (let i = 0; i < str.length; i++) {
        let code = str.charCodeAt(i);
        let hexCode = code.toString(16);
        hex += ('00' + hexCode).slice(-2);
    }
    return hex.toUpperCase();
}

export default RouterPlugin;
